package ex1;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

/** 
 * 
 * @author Dennis Meyer, Sebastian Brodehl, Sebastian Schappert
 *
 */

public class CVDataIO 
{

	public CVDataIO()
	{
	}
	
	/**
	 * Reads the file and give a CVData object back
	 * 
	 * @return The CVData object
	 */
	public CVData readCVFile(String filePath)
	{
		CVData cvData = new CVData();
		File tempFile = new File(filePath);
		
		try 
		{
			// Check if File exist
			if (!tempFile.exists())
				throw new FileNotFoundException("File does not exist!");
			
			try
			{

				BufferedReader reader = new BufferedReader
						(new InputStreamReader
						(new FileInputStream(filePath),"UTF-8"));
				
				if (!reader.readLine().toLowerCase().equals("#latexdoc")){
					reader.close();
					throw new Exception("File is invalid!");
				}
				
			    String line = null;
			    while((line = reader.readLine()) != null && !line.equals("#enddoc"))
			    {
			    	switch (line) 
			    	{
			    		case "*themestyle":
							cvData.setThemeStyle(reader.readLine());
							break;
			    		case "*themecolor":
							cvData.setThemeColor(reader.readLine());
							break;
			    		case "*givenName":
							cvData.setGivenName(reader.readLine());
							break;
						case "*lastName":
							cvData.setLastName(reader.readLine());
							break;
						case "*photoPath":
							cvData.setPhotoPath(reader.readLine());
							break;
						case "*street":
							cvData.setStreet(reader.readLine());
							break;
						case "*course":
							cvData.setCourse(reader.readLine());
							break;
						case "*mobileNumber":
							cvData.setMobileNumber(reader.readLine());
							break;
						case "*email":
							cvData.setEmail(reader.readLine());
							break;
						case "--section":
							CVSection section = new CVSection();
							section.setName(reader.readLine().split(",")[1]);
							section.setComment(reader.readLine().split(",")[1]);
							
							int elementCount = Integer.parseInt(reader.readLine());
							for (int i = 0; i < elementCount; i++) 
							{
								String tempLine = reader.readLine();
								if (tempLine.equals("-cventry"))
									section.getCvEntrys().add(reader.readLine().split(","));
								else if (tempLine.equals("-cvline"))
									section.getCvLines().add(reader.readLine().split(","));
							}
							cvData.getSections().add(section);
							break;
						default:
							throw new Exception("Reads an unknown sign!");
					}
			    }
			    reader.close();
			}
			catch(IOException e)
			{
				System.out.println("Error: " + e.getMessage());
			}
		} 
		catch (Exception ex)
		{
			System.out.println("Error: " + ex.getMessage());
		}
		
		return cvData;
	}

	/**
	 * Writes the given CVData in a file.
	 * 
	 * @param CVData The CVData object
	 * @return If the writes operation succeded.
	 */
	public boolean writeCVData(CVData cvData, String filePath)
	{
		File tempFile = new File(filePath);

		try 
		{
			
			// Check if File exist
			if (!tempFile.exists())
				tempFile.createNewFile();
			
			if (!tempFile.canWrite())
				throw new Exception("Not permissions to write in file!");
			
			try
			{
				BufferedWriter writer = new BufferedWriter
						(new OutputStreamWriter
						(new FileOutputStream(filePath),"UTF-8"));
				
				// Make file empty
				writer.write((new String()).toCharArray());
				writer.flush();
				
				writer.write("#latexdoc" + System.lineSeparator());
				writeMetaDatas("themestyle", cvData.getStyle().toString(), writer);
				writeMetaDatas("themecolor", cvData.getColor().toString(), writer);
				writeMetaDatas("givenName", cvData.getGivenName(), writer);
				writeMetaDatas("lastName", cvData.getLastName(), writer);
				writeMetaDatas("photoPath", cvData.getPhotoPath(), writer);
				writeMetaDatas("street", cvData.getStreet(), writer);
				writeMetaDatas("course", cvData.getCourse(), writer);
				writeMetaDatas("mobileNumber", cvData.getMobileNumber(), writer);
				writeMetaDatas("email", cvData.getEmail(), writer);
				
				for(CVSection section : cvData.getSections())
				{
					writer.write("--section" + System.lineSeparator());
					writer.write("-name," + section.getName() + System.lineSeparator());
					writer.write("-comment," + section.getComment() + System.lineSeparator());
					writer.write(section.getCvEntrys().size() + section.getCvLines().size() + System.lineSeparator());
					for (int i = 0; i < section.getCvEntrys().size(); i++) 
					{
						writer.write("-cventry" + System.lineSeparator());
						writer.write(CVDataIO.join(section.getCvEntrys().get(i), ",") + System.lineSeparator());
					}
					for (int i = 0; i < section.getCvLines().size(); i++) 
					{
						writer.write("-cvline" + System.lineSeparator());
						writer.write(CVDataIO.join(section.getCvLines().get(i), ",") + System.lineSeparator());
					}
				}
				
				writer.write("#enddoc");
				writer.close();
			}
			catch(IOException e)
			{
				System.out.println("Error : " + e.getMessage());
			}
		} 
		catch (Exception ex)
		{
			System.out.println("Error : " + ex.getMessage());
		}
		
		return true;
	}

	private void writeMetaDatas(String name, String value, BufferedWriter writer) throws IOException 
	{
		writer.write("*"+ name + System.lineSeparator());
		writer.write(value + System.lineSeparator());
	}

	private static String join(String[] s, String delimiter)
	{
		StringBuilder builder = new StringBuilder();
		
		for (int i = 0; i < s.length; i++) 
	    {
			 builder.append(s[i]);
			 if (i != s.length - 1)
				 builder.append(delimiter);
		}
	    return builder.toString();
	 }
}

